import type { Axios, AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';

import axios from 'axios';
import NProgress from 'nprogress';

import { message } from '@/App';
import userStore from '@/stores/user';
import { isDef, recordValueTrim } from '@/utils/CommonUtils';
import storage, { TOKEN } from '@/utils/StorageUtils';

import 'nprogress/nprogress.css';

NProgress.configure({ showSpinner: false });

const instance: AxiosInstance = axios.create({
  // baseURL: 'http://47.113.200.153:32570/xf/jointMes/api', // 外网
  // baseURL: 'https://40157bx61iq1.vicp.fun/xf/jointMes/api', // 外网
  baseURL: '/xf/jointMes/api', // 生产使用此版本
}) as AxiosInstance;

const noAuth = () => {
  const state = userStore.getState();
  state.clear();
  window.location.hash = '#/login';
};

instance.interceptors.request.use(
  config => {
    NProgress.start();
    const token = storage.get(TOKEN);
    // 如果在请求配置中指定了token，则不再添加token
    if (isDef(token) && !config?.headers?.Authorization) {
      // config.headers.Authorization = token as string;
    }

    // 处理get请求参数值字符串左右空格
    if (config.params) {
      config.params = recordValueTrim(config.params);
    }
    // 处理post请求参数值字符串左右空格
    if (config.data?.constructor === Object) {
      const data = recordValueTrim(config.data);
      config.data = data;
    }
    return config;
  },
  error => Promise.reject(error)
);

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    NProgress.done();
    // 下载文件
    if (response.data instanceof Blob) {
      return response;
    }

    if (response?.data?.code !== 200) {
      message.error(response.data.message);
      return Promise.reject(response.data);
    }
    return response.data;
  },
  async error => {
    NProgress.done();
    const { status, config } = error.response || {};
    if (status === 400) {
      message.error(`请求参数错误：${config.url}`);
    } else if (status === 401) {
      noAuth();
      return Promise.reject(error.data);
    } else if (status === 404) {
      message.error(`未找到接口：${config.url}`);
    } else if (status === 500) {
      message.error(`接口：${config.url}在服务端发生未知错误`);
    }
    return Promise.reject(error);
  }
);

export default instance;

export interface AxiosInstance extends Axios {
  (config: AxiosRequestConfig): Response<any>;
  (url: string, config?: AxiosRequestConfig): AxiosPromise;
}
export type Response<T = unknown> = Promise<ResponseBody<T>>;
export interface ResponseBody<T> extends AxiosResponse {
  code: number;
  data: T;
  message: string;
}
export interface ResponseDataList<T> {
  pageNo?: number;
  pageSize?: number;
  records: T[];
  totalRecord: number;
}
// 分页参数
export interface PaginationParams {
  pageNo?: number;
  pageSize?: number;
}
